package com.itealabs.postjson.ext;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;

import com.itealabs.postjson.JsonCallWaiter;
import com.itealabs.postjson.JsonCallWaiterLocator;

/**
 * Dispatch calls to matched JsonCallWaiterLocator, according to Regular Expression Patterns. 
 * @version $Id: JsonCallLobbyManager.java 5 2010-04-18 15:01:31Z iteahere $
 * @author itea
 * 2010-4-18
 */
public class JsonCallLobbyManager implements JsonCallWaiterLocator {

	private Map<Pattern, JsonCallWaiterLocator> waiterMap
		= Collections.synchronizedMap(new HashMap<Pattern, JsonCallWaiterLocator>());
	
	public JsonCallWaiter getCallWaiter(String method) {
		for(Entry<Pattern, JsonCallWaiterLocator> e : waiterMap.entrySet()) {
			if(e.getKey().matcher(method).matches()) {
				JsonCallWaiter waiter = e.getValue().getCallWaiter(method);
				if(waiter != null) return waiter;
			}
		}
		return null;
	}

	public void putWaiterLocator(Pattern p, JsonCallWaiterLocator wl) {
		this.waiterMap.put(p, wl);
	}
	
	public void putWaiterLocator(String p, JsonCallWaiterLocator wl) {
		this.waiterMap.put(Pattern.compile(p), wl);
	}
	
	public void setWaiterLocatorMap(Map<String, JsonCallWaiterLocator> locatorsmap) {
		for(Entry<String, JsonCallWaiterLocator> e : locatorsmap.entrySet()) {
			putWaiterLocator(Pattern.compile(e.getKey()), e.getValue());
		}
	}
}
